package view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.rmi.RemoteException;

import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;


import server.FirewallException;
import server.FirewallSession;
import server.NotExpertException;
import server.ReadWriteException;
import server.Rule;
import server.RulesTableType;


public class RuleAddFrame extends AbstractStandartFrame
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -9005665545823599377L;

	/**
	 * server controller
	 */
	private FirewallSession UI;
	
	/* Rule form */
	private RuleTable rule = null;
	
	/* Rule direction options names */
	private final String[] radioButtonsNames = {"In", "Out"};
	
	/* Radio buttons */
	private JRadioButton[] radioButtons = new JRadioButton[radioButtonsNames.length];
	
	/**
	 * C'tor
	 * Define the frame
	 */
	public RuleAddFrame(FirewallSession UI)
	{
	    super("Add rule");
	    this.UI = UI;
	    
	    setSize(new Dimension(300,150));
	    setLayout(new BorderLayout());
	    
		/* Table */
		rule = new RuleTable();
		
		/* Label adding */
		JPanel n = new JPanel(new BorderLayout());
		JLabel label = new JLabel("New rule:");
		n.add(label, BorderLayout.NORTH);

		/* Radio buttons */
		ButtonGroup group = new ButtonGroup();
		JPanel directions = new JPanel(new GridLayout(1,2));
		
		/* Add all radio buttons to group and to the window */
		for(int i = 0; i < radioButtons.length; i++)
		{
			radioButtons[i] = new JRadioButton();
			radioButtons[i].setText(radioButtonsNames[i]);
			group.add(radioButtons[i]);
			directions.add(radioButtons[i]);
		}
		radioButtons[0].setSelected(true);
		n.add(directions, BorderLayout.SOUTH);
		
		JPanel table = new JPanel();
		
		/* Header adding */
		table.setLayout(new BorderLayout());
		table.add(rule.getRulesTableHeader(), BorderLayout.NORTH);
		rule.getTableHeader().setReorderingAllowed(false);	
		
		/* Table adding */
		JScrollPane scrollpane = new JScrollPane(rule);
		scrollpane.getViewport().setPreferredSize(new Dimension(30,30));
		table.add(scrollpane,  BorderLayout.CENTER);
	
		add(n, BorderLayout.NORTH);
		add(table, BorderLayout.CENTER);
	    addStandartButtons();
	}

	/**
	 * Action performed by finish button press:
	 * new rule is passed to FW, tables are updated 
	 */
	protected void finishAction()
	{
		try{
			/* Get direction from radio boxes */
			Rule new_rule = rule.getRule();
			
			if(radioButtons[0].isSelected()){
				RulesAdvancedTable.currentInRulesAdvancedTable.addRule (RulesTableType.IN,new_rule);
			}
			else{
				RulesAdvancedTable.currentOutRulesAdvancedTable.addRule(RulesTableType.OUT,new_rule);
			}
			dispose();
			
			
		} catch (FirewallException e) {
			ErrorFrame.AddError(e.getMessage(), this);
		}
		
	}		
}
